<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类" prop="category">
        <el-input
          v-model="queryParams.category"
          placeholder="请输入商品分类"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

<!--    <el-row :gutter="10" class="mb8">-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['client:goods:add']"-->
<!--        >新增-->
<!--        </el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['client:goods:edit']"-->
<!--        >修改-->
<!--        </el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['client:goods:remove']"-->
<!--        >删除-->
<!--        </el-button>-->
<!--      </el-col>-->
<!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
<!--    </el-row>-->

    <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
<!--      <el-table-column label="序号" align="center" prop="id"/>-->
      <el-table-column label="商品名" align="center" prop="name" :show-overflow-tooltip="true" width="300"/>
      <el-table-column label="价格" align="center" prop="price"/>
      <el-table-column label="销量计数" align="center" prop="sellCount"/>
<!--      <el-table-column label="库存" align="center" prop="stock"/>-->
      <el-table-column label="分类" align="center" prop="category"/>
<!--      <el-table-column label="是否上架" align="center" prop="isOnSale">-->
<!--        <template slot-scope="scope">-->
<!--          <dict-tag :options="dict.type.man_goodsm_sale" :value="scope.row.isOnSale"/>-->
<!--        </template>-->
<!--      </el-table-column>-->

<!--      <el-table-column label="创建者" align="center" prop="createBy" width="120"/>-->
<!--      <el-table-column label="创建时间" align="center" prop="createTime" width="180"/>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="small"
            type="primary"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"

          >加入购物车
          </el-button>
          <el-button
            size="small"
            type="success"
            icon="el-icon-delete"
            @click="handleBuy(scope.row)"

          >立即购买
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加加入购物车对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body>
      <!-- 商品信息部分 -->
      <el-row>
        <el-col :span="12">
          <el-text style="font-weight: bold;">商品名：</el-text>
          <el-text>{{ form.name }}</el-text>
        </el-col>
        <el-col :span="12">
          <el-text style="font-weight: bold;">商品价格：</el-text>
          <el-text>{{ form.price }}</el-text>
        </el-col>
      </el-row>

      <!-- 分割线 -->
      <el-divider></el-divider>

      <!-- 表单部分 -->
      <el-form ref="car" :model="car" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="数量" prop="num">
              <el-input-number
                v-model="car.num"
                @change="handleChange"
                :min="1"
                :max="100"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 底部操作按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCar(car , form )">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 立即购买对话框 -->
    <el-dialog :title="title" :visible.sync="buyOpen" width="780px" append-to-body>
      <!-- 商品信息部分 -->
      <el-row>
        <el-col :span="12">
          <el-text style="font-weight: bold;">商品名：</el-text>
          <el-text>{{ form.name }}</el-text>
        </el-col>
        <el-col :span="12">
          <el-text style="font-weight: bold;">商品价格：</el-text>
          <el-text>{{ form.price }}</el-text>
        </el-col>
      </el-row>
      <!-- 分割线 -->
      <el-divider></el-divider>
      <!-- 表单部分 -->
      <el-form ref="car" :model="car" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="数量" prop="num">
              <el-input-number
                v-model="deal.count"
                @change="handleChangeBuy"
                :min="1"
                :max="100"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <!-- 实时总价显示 -->
          <el-col :span="12" style="display: flex; align-items: center;">
            <span style="font-weight: bold; margin-right: 5px;">总价：</span>
            <span>{{ isNaN(totalPrice) ? 0 : totalPrice }}</span>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="收货地址" prop="addressId">
              <el-select v-model="deal.addressId" placeholder="请选择收货地址" style="width: 100%">
                <el-option
                  v-for="item in addressList"
                  :key="item.id"
                  :label="item.province + ' ' + item.city + ' ' + item.district + ' - 收件人：' + item.consignee + ' 电话：' + item.phone"
                  :value="item.id">
                  <span style="float: left">{{ item.province + ' ' + item.city + ' ' + item.district }}</span>
                  <span style="float: right; font-size: 13px">收件人：{{ item.consignee }} 电话：{{ item.phone }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-radio-group v-model="deal.paymentMethod">
              <el-radio :label="3">微信支付</el-radio>
              <el-radio :label="6">支付宝支付</el-radio>
              <el-radio :label="9">银联支付</el-radio>
            </el-radio-group>
          </el-col>
        </el-row>
      </el-form>

      <!-- 底部操作按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBuy(deal , form )">确 定</el-button>
        <el-button @click="buyCancel">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { addGoods_m, delGoods_m, getGoods_m, listGoods_m, updateGoods_m, addCar} from '@/api/client/goods'

import { listAddress } from '@/api/client/address'

import { addDeal } from '../../../api/client/deal'

export default {
  name: 'Goods_m',
  dicts: ['sys_goods_status', 'sys_goods_type' , 'man_goodsm_sale'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品管理表格数据
      goodsList: [],
      // 弹出层标题
      title: '',
      // 是否显示加入购物车弹出层
      open: false,
      // 是否显示加入购物车弹出层
      buyOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        category: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      //购物车参数
      car: {
        num : 1,
        goodsId : null
      },
      //订单参数
      deal:{
        count: 1,
        addressId: null,
        paymentMethod: 3  // 3-微信支付，6-支付宝支付，9-银联支付
      },
      // 表单校验
      rules: {
        goodsTitle: [
          { required: true, message: '商品管理标题不能为空', trigger: 'blur' }
        ],
        goodsType: [
          { required: true, message: '商品管理类型不能为空', trigger: 'change' }
        ]
      },
      // 地址列表
      addressList: []
    }
  },
  created() {
    this.getList()
  },
  computed: {
    totalPrice() {
      // 如果价格为数字，则直接相乘，并保留两位小数
      return (this.form.price * this.deal.count).toFixed(2);
    }
  },
  methods: {
    /** 查询商品管理列表 */
    getList() {
      this.loading = true
      listGoods_m(this.queryParams).then(response => {
        this.goodsList = response.data
        this.total = response.total
        this.loading = false
      })
    },
    // 加入购物车取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 立即购买取消按钮
    buyCancel(){
      this.buyOpen = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        goodsTitle: undefined,
        goodsType: undefined,
        goodsContent: undefined,
        status: '0'
      }
      this.car = {
        num : 1,
        goodsId : null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加商品管理'
    },
    /** 加入购物车按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getGoods_m(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '添加购物车'
      })
    },



    /** 加入购物车操作 */
    // handleAddCar(row){
    //   this.reset()
    //   // const id = row.id || this.ids
    //   const car = {
    //     clientId : "",
    //   }
    //   addCar(id).then(response =>{
    //
    //   })
    // },

    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateGoods_m(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addGoods_m(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 添加购物车提交按钮 */
    submitCar(car ,form) {
      car.goodsId = form.id
      console.log(car)
      addCar(car).then(response =>{
        this.$modal.msgSuccess('添加成功')
        this.open = false
      })
    },
    /** 立即购买提交按钮 */
    submitBuy(deal ,form) {
      deal.goodsId = form.id
      console.log(deal)
      addDeal(deal).then(response =>{
        this.$modal.msgSuccess('下单成功')
        this.buyOpen = false
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除商品管理编号为"' + ids + '"的数据项？').then(function() {
        return delGoods_m(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 立即购买按钮操作 */
    handleBuy(row){
      this.reset()
      const id = row.id || this.ids
      Promise.all([
        getGoods_m(id),
        this.getAddressList()
      ]).then(([goodsRes]) => {
        this.form = goodsRes.data
        this.buyOpen = true
        this.title = '立即购买'
      })
    },
    /** 获取地址列表 */
    getAddressList() {
      return listAddress().then(response => {
        this.addressList = response.data || []
      })
    },
    /** 实时金额 */
    handleChangeBuy(){
      // totalPrice()
    }
  }
}
</script>
